package com.stack.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author llz
 * @date 2023/11/16 10:54
 * @description HttpClient工具类
 */
public class HttpUtil {

    private HttpUtil() {
        throw new IllegalStateException("Utility class");
    }

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    private static final int HTTP_OK = 200;

    /**
     * get请求
     *
     * @return
     */
    public static String doGet(String url) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * get请求
     *
     * @return
     */
    public static String doGet(String url, Map<String, String> headers) {
        try {
            HttpClient client = HttpClientBuilder.create().build();
            //发送get请求
            HttpGet request = new HttpGet(url);
            for (String key : headers.keySet()) {
                request.setHeader(key, headers.get(key));
            }
            HttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * post请求(用于key-value格式的参数)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, String> params) throws Exception {
        // 定义HttpClient
        HttpClient client = HttpClientBuilder.create().build();
        // 超时配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(30*1000)
                .setSocketTimeout(30*1000)
                .setConnectTimeout(30*1000).build();
        // 实例化HTTP方法
        HttpPost request = new HttpPost();
        request.setURI(new URI(url));
        request.setConfig(requestConfig);

        //设置参数
        List<NameValuePair> nvps = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();
            nvps.add(new BasicNameValuePair(name, value));
        }
        request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));

        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();
        if (code == HTTP_OK) {
            try (
                    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
            ) {
                StringBuilder sb = new StringBuilder();
                String line;
                String nl = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line).append(nl);
                }
                return sb.toString();
            }
        } else {
            logger.info("状态码：{}", code);
        }
        return null;
    }

    /**
     * post请求(用于key-value格式的参数，带请求头)
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPostWithHeaders(String url, Map headers, Map params) {

        BufferedReader in;
        try {
            // 定义HttpClient
            HttpClient client = HttpClientBuilder.create().build();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));
            for (Object key : headers.keySet()) {
                request.setHeader(key.toString(), headers.get(key).toString());
            }

            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Object o : params.keySet()) {
                String name = (String) o;
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
                StringBuilder sb = new StringBuilder();
                String line;
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                return sb.toString();
            } else {
                logger.info("状态码：{}", code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);        // 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(2 * 60 * 1000).build();
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity, charSet);
            } else {
                logger.error("请求返回: {} ( {} )", state, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * post请求（用于请求url带Parameter的json格式的参数）
     * @param url
     * @param parameters
     * @param body
     * @return
     */
    public static String doPostWithParameters(String url, Map<String, String> parameters, String body) {
        HttpPost httpPost = null;
        try {
            URIBuilder uri = new URIBuilder(url);
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                uri.setParameter(entry.getKey(), entry.getValue());
            }
            httpPost = new HttpPost(uri.build());
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("Content-Type", "application/json");

            StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(2 * 60 * 1000).build();
            httpPost.setConfig(requestConfig);
        } catch (Exception e) {
            logger.error("http post 请求构建 HttpPost 异常！！！", e);
        }
        if (httpPost != null) {
            try (
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    CloseableHttpResponse response = httpclient.execute(httpPost)
            ) {
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                } else {
                    logger.info("http post 请求返回: {} ( {} )", state, httpPost.getURI());
                }
            } catch (Exception e) {
                logger.error("http post 请求异常！！！", e);
            }
        }
        return null;
    }

    /**
     * post请求（用于请求url带Parameter的json格式的参数）
     * @param url
     * @param parameters
     * @param body
     * @return
     */
    public static String doPostWithParameters(String url, Map<String, String> parameters, Map<String, String> headers, String body) {
        HttpPost httpPost = null;
        try {
            URIBuilder uri = new URIBuilder(url);
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                uri.setParameter(entry.getKey(), entry.getValue());
            }
            httpPost = new HttpPost(uri.build());
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(2 * 60 * 1000).build();
            httpPost.setConfig(requestConfig);
        } catch (Exception e) {
            logger.error("http post 请求构建 HttpPost 异常！！！", e);
        }
        if (httpPost != null) {
            try (
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    CloseableHttpResponse response = httpclient.execute(httpPost)
            ) {
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                } else {
                    logger.info("http post 请求返回: {} ( {} )", state, httpPost.getURI());
                }
            } catch (Exception e) {
                logger.error("http post 请求异常！！！", e);
            }
        }
        return null;
    }

    public static String doPost(String url, Map<String, String> headers, String params) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Keep-Alive");
        httpPost.setHeader("User-Agent", "PostmanRuntime/7.30.0");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }

        String charSet = "UTF-8";
        StringEntity entity = null;
        if (StringUtils.isNotBlank(params)) {
            entity = new StringEntity(params, charSet);
        }
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity, charSet);
            } else {
                logger.error("请求返回: {} ( {} )", state, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String doPost(String url, Map<String, String> parameters,
                                      Map<String, String> headers, Map<String, String> bodies) throws Exception {
        HttpPost httpPost = null;
        try {
            URIBuilder uri = new URIBuilder(url);
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                uri.setParameter(entry.getKey(), entry.getValue());
            }
            httpPost = new HttpPost(uri.build());
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            if (bodies != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

                for (String key : bodies.keySet()) {
                    nameValuePairList.add(new BasicNameValuePair(key, bodies.get(key)));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                httpPost.setEntity(formEntity);
            }

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(2 * 60 * 1000).build();
            httpPost.setConfig(requestConfig);
        } catch (Exception e) {
            logger.error("http post 请求构建 HttpPost 异常！！！", e);
        }
        if (httpPost != null) {
            try (
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    CloseableHttpResponse response = httpclient.execute(httpPost)
            ) {
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                } else {
                    logger.info("http post 请求返回: {} ( {} )", state, httpPost.getURI());
                }
            } catch (Exception e) {
                logger.error("http post 请求异常！！！", e);
            }
        }
        return null;
    }

    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL realUrl = new URL(null, strUrl, new sun.net.www.protocol.https.Handler());
            HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将图片写入到磁盘
     *
     * @param img
     * @param fileName
     */
    public static void writeImageToDisk(byte[] img, String fileName) {
        try {
            File file = new File(fileName);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            logger.info("图片已经写入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

}
